import { authEmail } from '@/api/flow/auth';

export default {
   data() {
    return {
      // form
      form: this.$form.createForm(this),

      // state
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    };
  },

  methods: {
    // send code email
    sendEmailCode() {
      const fields = ['email'];
      const { first_name, last_name } = this.currentUser;
      const data = {
        first_name,
        last_name,
        ...this.form.getFieldsValue(fields)
      };
      this.sendCode(fields, data);
    },

    handleSubmit() {
      const { state } = this;

      state.loginBtn = true;

      return new Promise((resolve, reject) => {
        this.validateFieldsForm()
          .then(() => {
            this.submitForm()
              .then(async (data) => {
                try {
                  await this.$store.dispatch('GetInfo');
                  state.loginBtn = false;
                  resolve(data);
                } catch (error) {
                  state.loginBtn = false;
                  reject(error);
                }
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                state.loginBtn = false;
              });
          })
          .catch((error) => {
            reject(error);
            state.loginBtn = false;
          });
      });
    },

    submitCallBack() {
    },

    resetFields() {
      this.resetCodeStatus();

      this.form.resetFields();
    },

    // form validateFields
    validateFieldsForm() {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFields }
        } = this;

        const validateFieldsKey = ['email', 'code'];

        validateFields(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve();
            return false;
          }
          reject(false);
        });
      });
    },

    // Retrieve password
    submitForm() {
      const validateFieldsKey = ['email', 'code'];

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey);

        authEmail(fields)
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};
